package servlet.img;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet({"/load"})
public class LoadImg extends HttpServlet {
    private static final String path = "D:\\Program Files\\ideaProgram\\updateFiles";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp){
//
        String filename = req.getParameter("filename");
        System.out.println("获取图片："+filename);
        try{
            FileInputStream fis = new FileInputStream(new File(path, filename));
//        预览
//        resp.setHeader("Content-Disposition", "fName="+fName);
//        下载
//        resp.setHeader("Content-Disposition", "attachment;filename="+fName);
            resp.setHeader("Content-Disposition","filename="+filename);
            ServletOutputStream out = resp.getOutputStream();
//        读取文件
            byte[] bytes = new byte[1024];
            int len = 0;
            while((len  = fis.read(bytes)) != -1){
                out.write(bytes,0,len);
            }
            out.close();
            fis.close();
        }catch (Exception e){
            log(e.getMessage());
//            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}